package com.guang.lock.condition;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description 测试下面代码出现死循环的原因
 *              是因为t1线程持有锁的阶段中，在while循环中调用了sleep方法，而这个方法不会将锁释放掉
 * @Author liguang
 * @Date 2022/10/20/17:59
 */
public class ConditionSetSleepTest {
    private final static Logger logger = LoggerFactory.getLogger(ConditionSetSleepTest.class);
    static boolean flag = false;

    static ReentrantLock lock = new ReentrantLock();


    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            lock.lock();
            while (!flag){
                logger.info("当前线程因为不满足flag=true而进入到条件队列中阻塞");
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            logger.info("当前线程被唤醒，开始执行临界区代码");
            lock.unlock();
        }, "t1");

        t1.start();

        logger.info("当前共享变量flag为：{}",flag);

        lock.lock();
        logger.info("开始唤醒在conditionSet中阻塞的线程");
        flag = true;
        lock.unlock();
        logger.info("main线程执行结束");
    }

}
